package org.docshare.zhuishu;

import net.tsz.afinal.FinalDb;

import org.docshare.http.CapCache;
import org.docshare.http.DataServer;
import org.docshare.http.YangResponse;
import org.docshare.view.BatteryTool;
import org.docshare.view.ReadViewNew;

import cn.edu.hfut.dmic.htmlbot.contentextractor.ContentExtractor;

import android.app.Activity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

public class ReaderActivity extends Activity implements YangResponse {
	private static final String TAG = "ReadActivity";

	TextView tv;
	ReadViewNew readView;
	FinalDb  db ;

	private String url;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,   
				WindowManager.LayoutParams.FLAG_FULLSCREEN);  
		requestWindowFeature(Window.FEATURE_NO_TITLE); 
		
		
		url = this.getIntent().getStringExtra("url");
		Log.i(TAG,"url is "+url);
		if(url == null){
			Toast.makeText(this, "程序有误",Toast.LENGTH_LONG).show();
			return;
		}
		BatteryTool.getIns().start(this);
		setContentView(R.layout.activity_reader);
		readView = (ReadViewNew) findViewById(R.id.readView);
		
		db = FinalDb.create(this);
		CapCache cache = db.findById(url, CapCache.class);
		if(cache != null){
			Log.i(TAG, "load from cache :"+cache.title);
			readView.setText(cache.content,cache.title);
		}else{
			DataServer.getIns(this).read(url, this);
		}
		//tv = (TextView) findViewById(R.id.tbShow);
		//tv.setMovementMethod(ScrollingMovementMethod.getInstance()); 
		
		

	}

	@Override
	public void onResult(boolean succ, Object response) {
		//tv.setText(response.toString());
		String s = (String) response;
		
		try {
			s = s.replace("&nbsp;", "").replace(" ", "").replace("\t", "");
			String content = ContentExtractor.getContentByHtml(s);
			String title = this.getIntent().getStringExtra("title");
			Log.i(TAG,content.toString());
			readView.setText(content,title);
			CapCache cache = new CapCache();
			cache.setId(url);
			cache.setContent(content);
			cache.setTitle(title);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	@Override
	protected void onDestroy() {
		BatteryTool.getIns().stop(this);
		super.onDestroy();
	}
}
